package com.android.rundemo.ui.fragment;


import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.android.rundemo.R;
import com.android.rundemo.ui.activity.SettingActivity;
import com.android.rundemo.utils.GlobalUtil;
import com.hb.dialog.myDialog.MyAlertInputDialog;
import com.robinhood.ticker.TickerUtils;
import com.robinhood.ticker.TickerView;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import cn.qqtheme.framework.picker.NumberPicker;
import cn.qqtheme.framework.picker.OptionPicker;

public class ProfileFragment extends Fragment {

    public static final String TAG = "ProfileFragment";

    Context context;

    //总距离、总时间
    TickerView tv_sumOfDistance, tv_sumOfTimes;
    int sumOfDistance = 0, sumOfTimes = 0;

    //修改个人数据
    ImageButton ib_editName, ib_editAge, ib_editHeight, ib_editWeight;

    TextView tv_name, tv_age, tv_height, tv_weight;

    //个人信息文件名
    String fileName = "personalData";

    //设置
    RelativeLayout rl_setting;


    public ProfileFragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_profile, container, false);

        context = view.getContext();

        //初始化
        tv_sumOfDistance = view.findViewById(R.id.tv_sumOfDistance);
        tv_sumOfDistance.setCharacterLists(TickerUtils.provideNumberList());
        tv_sumOfDistance.setAnimationDuration(1000);


        tv_sumOfTimes = view.findViewById(R.id.tv_sumOfTimes);
        tv_sumOfTimes.setCharacterLists(TickerUtils.provideNumberList());
        tv_sumOfTimes.setAnimationDuration(1000);

        tv_name = view.findViewById(R.id.tv_name);
        tv_age = view.findViewById(R.id.tv_age);
        tv_height = view.findViewById(R.id.tv_height);
        tv_weight = view.findViewById(R.id.tv_weight);

        //编辑昵称
        ib_editName = view.findViewById(R.id.ib_editName);
        ib_editName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final MyAlertInputDialog myAlertInputDialog = new MyAlertInputDialog(view.getContext()).builder()
                        .setTitle("请输入")
                        .setEditText("");
                myAlertInputDialog.setPositiveButton("确认", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String name = myAlertInputDialog.getResult();
                        if (name.length() == 0) {
                            Toast.makeText(view.getContext(), "昵称不能为空!", Toast.LENGTH_SHORT).show();
                        } else if (name.length() > 8) {
                            Toast.makeText(view.getContext(), "昵称不能超过8个字节!", Toast.LENGTH_SHORT).show();
                        } else {
                            tv_name.setText(name);
                            Toast.makeText(view.getContext(), "修改成功", Toast.LENGTH_SHORT).show();
                        }
                        myAlertInputDialog.dismiss();
                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        myAlertInputDialog.dismiss();
                    }
                });
                myAlertInputDialog.show();
            }
        });

        //修改年龄
        ib_editAge = view.findViewById(R.id.ib_editAge);
        ib_editAge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NumberPicker picker = new NumberPicker(getActivity());
                picker.setOffset(2);//偏移量
                picker.setRange(10, 100);//数字范围
                picker.setSelectedItem(20);
                picker.setLabel("岁");
                picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
                    @Override
                    public void onOptionPicked(String option) {
                        tv_age.setText(option);
                    }
                });
                picker.show();
            }
        });

        //修改身高
        ib_editHeight = view.findViewById(R.id.ib_editHeight);
        ib_editHeight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NumberPicker picker = new NumberPicker(getActivity());
                picker.setOffset(2);//偏移量
                picker.setRange(145, 200);//数字范围
                picker.setSelectedItem(170);
                picker.setLabel("厘米");
                picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
                    @Override
                    public void onOptionPicked(String option) {
                        tv_height.setText(option);
                    }
                });
                picker.show();
            }
        });

        //修改体重
        ib_editWeight = view.findViewById(R.id.ib_editWeight);
        ib_editWeight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NumberPicker picker = new NumberPicker(getActivity());
                picker.setOffset(2);//偏移量
                picker.setRange(40, 200);//数字范围
                picker.setSelectedItem(60);
                picker.setLabel("公斤");
                picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
                    @Override
                    public void onOptionPicked(String option) {
                        tv_weight.setText(option);
                    }
                });
                picker.show();
            }
        });


        //启动时设置头像等信息
        initView();

        //设置
        rl_setting = view.findViewById(R.id.rl_setting);
        rl_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), SettingActivity.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
            }
        });

        return view;
    }

    /**
     * 加载头像及个人信息
     */
    private void initView() {
        readPersonalData();
    }

    /**
     * 存储个人信息至本地
     */
    private void savePersonalData() {
        OutputStream outputStream = null;
        try {
            outputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
            String name = tv_name.getText().toString() + "\n";
            String age = tv_age.getText().toString() + "\n";
            String height = tv_height.getText().toString() + "\n";
            String weight = tv_weight.getText().toString() + "\n";

            bufferedWriter.write(name);
            bufferedWriter.write(age);
            bufferedWriter.write(height);
            bufferedWriter.write(weight);
            bufferedWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 读取个人信息
     */
    private void readPersonalData() {
        StringBuilder sBuilder = new StringBuilder();

        InputStream inputStream = null;
        try {
            inputStream = context.openFileInput(fileName);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String name, age, height, weight;

            //读取
            name = bufferedReader.readLine();
            age = bufferedReader.readLine();
            height = bufferedReader.readLine();
            weight = bufferedReader.readLine();

            //设置
            tv_name.setText(name);
            tv_age.setText(age);
            tv_height.setText(height);
            tv_weight.setText(weight);

            bufferedReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        //查询总距离并传给控件
        sumOfDistance = GlobalUtil.getInstance().databaseHelper.queryAllDistance();
        //格式 XX.X
        sumOfDistance /= 100;
        double sumOfDistanceInKM = sumOfDistance / 10.0;
        tv_sumOfDistance.setText(sumOfDistanceInKM + "");

        //查询总次数
        sumOfTimes = GlobalUtil.getInstance().databaseHelper.queryNumOfTimes();
        tv_sumOfTimes.setText(sumOfTimes + "");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //退出时存储数据
        savePersonalData();
    }
}
